package com.songshuai.webapi.permission.controller.feign;

import com.songshuai.webapi.baseapi.constant.BaseConstant;
import com.songshuai.webapi.baseapi.dto.feign.request.UserAddReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.UserInfoUpdateReqDto;
import com.songshuai.webapi.baseapi.dto.feign.response.*;
import com.songshuai.webapi.baseapi.dto.feign.response.DictionaryDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.EncryptUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.baseapi.utils.RequestParamValidUtil;
import com.songshuai.webapi.permission.controller.BaseController;
import com.songshuai.webapi.permission.dto.response.NavigationResDto;
import com.songshuai.webapi.permission.model.YxFunctions;
import com.songshuai.webapi.permission.model.YxUsers;
import com.songshuai.webapi.permission.service.FunctionsService;
import com.songshuai.webapi.permission.service.NavigationsService;
import com.songshuai.webapi.permission.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 对外提供服务
 * 账号管理
 * @Author: lhx
 * @Date: 2018/12/24 17:21
 */
@Slf4j
@RestController
@RequestMapping("/api/user/")
public class AccountController extends BaseController {


    @Autowired
    private UsersService usersService;

    @Autowired
    private FunctionsService functionsService;

    @Autowired
    private NavigationsService navigationsService;




    /**
     * 根据用户名或手机号模糊查询
     * @param account
     * @param status
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("queryUserInfoListByPage")
    public QueryResponse<QueryPageRes<List<AccountPageLIstResDto>>> queryUserInfoListByPage(@RequestParam(value = "account",required = false)String account
                                                    , @RequestParam(value = "status",required = false)Integer status
                                                    , @RequestParam(value = "pageIndex",defaultValue = "1")int pageIndex
                                                    , @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){

        return usersService.selectByMobileOrName(account, status, pageIndex, pageSize);
    }

    /**
     * 根据角色查询菜单以及功能
     * @param roleIds
     * @return
     */
    @RequestMapping("queryFunctionByRole")
    public QueryResponse<Map<Integer,List<NavAndFuncByRoleResDto>>> queryFunctionByRole(@RequestParam("roleIds")List<Integer> roleIds){
        Map<Integer,List<NavAndFuncByRoleResDto>> result = new HashMap<>();
        for (Integer roleId : roleIds) {
            result.put(roleId,functionsService.queryFunctionKeyByRole(roleId));
        }
        return QueryResponse.setResData(result);
    }


    /**
     * 根据菜单id获取菜单信息
     * @param ids 菜单id集合
     * @return
     */
    @RequestMapping("queryNavigationInfo")
    public QueryResponse<Map<Integer, NavigationInfoResDto>> queryNavigationInfo(@RequestParam("ids")List<Integer> ids){
        Map<Integer,NavigationInfoResDto> result = new HashMap<>();
        for (Integer id : ids) {
            NavigationResDto navigationResDto = navigationsService.queryNavigationById(id);
            if (null != navigationResDto){
                NavigationInfoResDto resDto = new NavigationInfoResDto();
                PropertiesUtil.copyProperties(navigationResDto,resDto);
                result.put(id,resDto);
            }
        }
        return QueryResponse.setResData(result);
    }





    /**
     * 根据功能id获取功能信息
     * @param ids 功能id集合
     * @return
     */
    @RequestMapping("queryFunctionInfo")
    public QueryResponse<Map<Integer, FunctionInfoResDto>> queryFunctionInfo(@RequestParam("ids")List<Integer> ids){
        Map<Integer,FunctionInfoResDto> result = new HashMap<>();
        for (Integer id : ids) {
            YxFunctions yxFunctions = functionsService.queryFunctionByFuncId(id);
            if (null != yxFunctions){
                FunctionInfoResDto resDto = new FunctionInfoResDto();
                PropertiesUtil.copyProperties(yxFunctions,resDto);
                result.put(id,resDto);
            }
        }
        return QueryResponse.setResData(result);
    }


    /**
     * 新增用户
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("addUser")
    public QueryResponse addUser(@RequestBody @Valid UserAddReqDto request, BindingResult result){
        if (result.hasErrors()){
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        String userId = getUserId()+"";
        try {
            if (getTokenLock(userId)){
                return usersService.addUser(request);
            }else {
                return new QueryResponse(ResultStatus.ERROR_REPEAT_OPERATION);
            }
        } catch (Exception e) {
            log.error("/api/user/addUser",e);
        } finally {
            relesesTokenLock(userId);
        }
        return new QueryResponse(ResultStatus.ERROR_CREATE_FAILED);
    }


    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @RequestMapping("queryUserInfoById")
    public QueryResponse<AccountInfoResDto> queryUserInfoById(@RequestParam("id")Integer id){
        return QueryResponse.setResData(usersService.selectUserById(id));
    }


    /**
     * 修改用户信息
     * @param requset
     * @param result
     * @return
     */
    @RequestMapping("updateUserById")
    public QueryResponse updateUserById(@RequestBody @Valid UserInfoUpdateReqDto requset, BindingResult result){
        if (result.hasErrors()){
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        if (usersService.updateUser(requset)){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);

    }

    /**
     * 禁用/启用
     * @param id
     * @return
     */
    @RequestMapping("updateUserStatusById")
    public QueryResponse updateUserStatusById(@RequestParam("id")Integer id,@RequestParam("status")Integer status){
        boolean b = usersService.updateByPrimaryKeySelective(new YxUsers() {{
            setId(id);
            setIsLeave(status);
        }});
        if (b){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }


    /**
     * 根据用户id修改密码
     * @param id
     * @param pwd
     * @return
     */
    @RequestMapping("updateUserPwdById")
    public QueryResponse updateUserPwdById(@RequestParam("id")Integer id,@RequestParam("pwd")String pwd){
        boolean b = usersService.updateByPrimaryKeySelective(new YxUsers() {{
            setId(id);
            setPassword(EncryptUtil.md5(pwd).substring(0, 20).toUpperCase());
            setUpdatePwdDate(new Date());
        }});
        if (b){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }


    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("deleteUserById")
    public QueryResponse deleteUserById(@RequestParam("id")Integer id){
        boolean b = usersService.updateByPrimaryKeySelective(new YxUsers() {{
            setId(id);
            setIsDelete(BaseConstant.IS_DELETE_FLAG_YES);
        }});
        if (b){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_DELETE_FAILED);
    }


    /**
     * 根据多个用户id查询用户信息
     * @param userIds
     * @return
     */
    @RequestMapping(value = "queryUserInfoByIds")
    public QueryResponse<List<AccountInfoListResDto>> queryUserInfoByIds(@RequestBody List<Integer> userIds){
        try{
            if(CollectionUtils.isNotEmpty(userIds)) {
                List<AccountInfoListResDto> resDtoList = usersService.queryUserInfoByIds(userIds);
                return QueryResponse.setResData(resDtoList);
            }
        }catch (Exception ex){
            log.error("queryUserInfoByIds",ex);
        }
        return QueryResponse.setResData(null, ResultStatus.ERROR_RECORD_NOT_FOUND);
    }


    /**
     * 根据校区查询出非userId的用户信息
     * @param userId
     * @param campusId
     * @return
     */
    @RequestMapping(value = "queryUserInfoListByCampusId")
    public QueryResponse<List<AccountInfoListResDto>> queryUserInfoListByCampusId(@RequestParam("userId")Integer userId,@RequestParam("campusId")Integer campusId){
        try{
            return QueryResponse.setResData(usersService.queryUserInfoListByCampusId(userId,campusId));
        }catch (Exception ex){
            log.error("queryUserInfoByIds",ex);
        }
        return QueryResponse.setResData(null, ResultStatus.ERROR_RECORD_NOT_FOUND);
    }

    /**
     * 根据真实姓名模糊查询用户信息
     * @param trueName
     * @param campusId
     * @return
     */
    @RequestMapping(value = "queryUserInfoListByTrueName")
    public QueryResponse<List<AccountInfoListResDto>> queryUserInfoListByTrueName(@RequestParam("trueName")String trueName,@RequestParam("campusId")Integer campusId){
        try{
            return QueryResponse.setResData(usersService.queryUserInfoListByTrueName(trueName,campusId));
        }catch (Exception ex){
            log.error("queryUserInfoListByTrueName",ex);
        }
        return QueryResponse.setResData(null, ResultStatus.ERROR_RECORD_NOT_FOUND);
    }

}
